﻿using System;
using System.Data.SqlClient;
using System.IO;
using System.Net;
using System.Text;
using System.Xml.Linq;

namespace Automator.Runtime
{
    /// <summary>
    /// A static class for application-wide settings
    /// </summary>
    public static class Settings
    {
        #region Properties

        public static WebProxy Proxy { get; set; }
        
        public static SqlConnectionStringBuilder SqlConnectionString { get; set; }

        #endregion

        #region Methods

        public static void ReadSettings(string source)
        {
            string xml = Automator.Runtime.Encryption.DecryptString(source);
            XElement settings = XDocument.Parse(xml).Element("Settings");

            //Proxy settings
            XElement proxyElement = settings.Element("Proxy");
            if (!String.IsNullOrEmpty(proxyElement.Attribute("Host").Value))
            {
                Automator.Runtime.Settings.Proxy = new WebProxy(
                    proxyElement.Attribute("Host").Value,
                    Convert.ToInt32(proxyElement.Attribute("Port").Value)
                    );
                Automator.Runtime.Settings.Proxy.BypassProxyOnLocal = Convert.ToBoolean(proxyElement.Attribute("BypassOnLocal").Value);
                if (!String.IsNullOrEmpty(proxyElement.Attribute("Username").Value))
                {
                    Automator.Runtime.Settings.Proxy.Credentials = new NetworkCredential(
                        proxyElement.Attribute("Username").Value,
                        proxyElement.Attribute("Password").Value
                        );
                }
            }
            
            //Database settings
            XElement sqlElement = settings.Element("Database");
            if (!String.IsNullOrEmpty(sqlElement.Attribute("Server").Value))
            {
                SqlConnectionStringBuilder sb = new SqlConnectionStringBuilder();
                sb.ApplicationName = "Automator";
                sb.DataSource = sqlElement.Attribute("Server").Value;
                sb.InitialCatalog = sqlElement.Attribute("Catalog").Value;
                sb.IntegratedSecurity = Convert.ToBoolean(sqlElement.Attribute("IntegratedSecurity").Value);
                sb.UserID = sqlElement.Attribute("Username").Value;
                sb.Password = sqlElement.Attribute("Password").Value;
                Automator.Runtime.Settings.SqlConnectionString = sb;
            }
        }
        
        public static string GetCryptedXML()
        {
            NetworkCredential credential = null; 
            if (Proxy!= null && Proxy.Credentials != null)
                credential = Proxy.Credentials.GetCredential(new Uri("http://www.ru"), "Basic");
            
            XDocument result = new XDocument(
                new XDeclaration("1.0", "utf-8", "yes"),
                new XComment("Automator Settings File"),
                new XElement("Settings",
                             new XElement("Proxy",
                                          new XAttribute("Host", (Proxy == null) ? String.Empty : Proxy.Address.Host),
                                          new XAttribute("Port", (Proxy == null) ? 0 : Proxy.Address.Port),
                                          new XAttribute("BypassOnLocal", (Proxy == null) ? true : Proxy.BypassProxyOnLocal),
                                          new XAttribute("Username", (credential != null) ? credential.UserName : String.Empty),
                                          new XAttribute("Password", (credential != null) ? credential.Password : String.Empty)
                                         ),
                             new XElement("Database",
                                          new XAttribute("Server", (SqlConnectionString == null) ? String.Empty : SqlConnectionString.DataSource),
                                          new XAttribute("Catalog", (SqlConnectionString == null) ? String.Empty : SqlConnectionString.InitialCatalog),
                                          new XAttribute("IntegratedSecurity", (SqlConnectionString == null) ? true : SqlConnectionString.IntegratedSecurity),
                                          new XAttribute("Username", (SqlConnectionString == null) ? String.Empty : SqlConnectionString.UserID),
                                          new XAttribute("Password", (SqlConnectionString == null) ? String.Empty : SqlConnectionString.Password)
                                         )
                            )
               );

            return Automator.Runtime.Encryption.EncryptString(result.ToString());
        }        
        
        public static void SaveSettings()
        {
            string xml = GetCryptedXML();
            using (StreamWriter sw = new StreamWriter(Path.Combine(Automator.Runtime.Environment.xmlDir, "settings.xml"),
                                                      false, Encoding.UTF8))
            {
                sw.Write(xml);
            }
        }

        #endregion
    }
}
